/*
 * Copyright (C) 2011 by Fabien Barbero
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.flickr.api;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Fabien Barbero
 */
public abstract class AbstractFlickrService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFlickrService.class);
    
    private static final String URL_PREFIX = "http://api.flickr.com/services/rest/";
    
    private static boolean debugEnabled = Boolean.parseBoolean(System.getProperty("flickr.api.debug", "false"));
    private static Client client;
    
    protected static synchronized Client getClient() {
        if(client == null) {
            ClientConfig clientConfig = new DefaultClientConfig();
            client = Client.create(clientConfig);
        }
        return client;
    }
    
    protected static <T extends ServerResponse> T doGet(CommandArguments args, Class<T> clazz) throws FlickrServiceException {
        ClientResponse resp = getClient().resource(args.toSignedQueryParams(URL_PREFIX)).get(ClientResponse.class);
        T entity = resp.getEntity(clazz);
        checkResponse(entity, args);
        if(debugEnabled) {
            try {
                LOGGER.debug("Server response for method '" + args.getMethod() + "'\n" +
                        getClient().resource(args.toSignedQueryParams(URL_PREFIX)).get(String.class) );
            } catch(Exception ignored) {
            }
        }
        return entity;
    }
    
    protected static <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz) throws FlickrServiceException {
        ClientResponse resp = getClient().resource(URL_PREFIX).type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, args.toSignedMultipart());
        if(debugEnabled) {
            LOGGER.debug("Server response for method '" + args.getMethod() + "'\n" + resp.getEntity(String.class) );
        }
        T entity = resp.getEntity(clazz);
        checkResponse(entity, args);
        return entity;
    }
    
    protected static void checkResponse(ServerResponse response, CommandArguments args) throws FlickrServiceException {
        if(response.getStatus() == ServerResponse.ResponseStatus.fail) {
            FlickrErrorCode errorCode = FlickrErrorCode.fromCode(response.getError().getCode());
            throw new FlickrServiceException("Error calling method '" + args.getMethod() + "' (" + response.getError().getMessage() + ")", errorCode);
        }
    }
    
}
